package com.black.utils.network.transmit.tcp;

import com.black.utils.commons.network.ServerThread;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 标准socket 的接收端
 *
 * @author ylx
 */
@Slf4j
public class TCPServer implements Closeable {
    private final ServerSocket serverSocket;

    public TCPServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        new TCPServerThread().start();
    }

    @Override
    public void close() throws IOException {
        serverSocket.close();
    }

    private class TCPServerThread extends ServerThread {
        private PrintWriter writer;
        private BufferedReader reader;

        @Override
        public void run() {
            String simpleName = this.getClass().getSimpleName();
            while (!serverSocket.isClosed()) {
                try (Socket socket = serverSocket.accept();
                     PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
                     BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    this.reader = reader;
                    String message = receive();
                    String response = handle(message);
                    this.writer = writer;
                    response(response);
                } catch (Exception e) {
                    log.error("server: {}; socket error: {}", simpleName, e.getMessage());
                }
            }
            log.info("server: {}; socket closed", simpleName);
        }

        @Override
        protected String receiveMsg() throws IOException {
            return reader.readLine();
        }

        @Override
        protected void responseMsg(String response) {
            writer.println(response);
        }
    }
}
